﻿namespace BorgExt.Behaviors
{
    public class ActivateBehavior : Behavior<Extension>
    {
        public ActivateBehavior(IRule<Extension> rule)
            : base(rule)
        { }

        public override void Activated(ExtensionEventArgs args)
        {
            Rule.Composed(args.Extension);
        }

        public override void Activating(ExtensionEventArgs args)
        {
            Rule.Composing(args.Extension);
        }

        public override void Bind(Slot slot)
        {
            base.Bind(slot);

            foreach (var plug in slot.PluggedPlugs)
            {
                Rule.AddCandidate(plug.Extension);

                if (plug.Extension.IsActivated)
                    Rule.Composed(plug.Extension);
            }
        }

        public override bool CanActivate(ExtensionEventArgs args, out LogEventArgs log)
        {
            return Rule.CanCompose(args.Extension, out log);
        }

        public override bool CanDeactivate(ExtensionEventArgs args, out LogEventArgs log)
        {
            return Rule.CanDecompose(args.Extension, out log);
        }

        protected override void Compose(Extension extension)
        {
            extension.Activate();
        }

        public override void Deactivated(ExtensionEventArgs args)
        {
            Rule.Decomposed(args.Extension);
        }

        public override void Deactivating(ExtensionEventArgs args)
        {
            Rule.Decomposing(args.Extension);
        }

        protected override void Decompose(Extension extension)
        {
            extension.Deactivate();
        }

        public override void Plugged(CompositionEventArgs args)
        {
            var plug = args.Plug;
            Rule.AddCandidate(plug.Extension);

            if (plug.Extension.IsActivated)
                Rule.Composed(plug.Extension);
        }

        public override void Unplugged(CompositionEventArgs args)
        {
            var plug = args.Plug;
            Rule.RemoveCandidate(plug.Extension);
        }
    }
}

